package com.quectel.business.common.grid;

import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridMemberGridBindingDto;
import com.quectel.core.module.grid.service.GridMemberGridBindingService;
import com.quectel.core.module.grid.service.GridService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/2/17 16:54
 * @description new java file header...
 */
@Component
public class GridBusiness {
    @DubboReference
    private GridMemberGridBindingService gridMemberGridBindingService;
    @DubboReference
    private GridService gridService;

    public List<GridDto> getMyGrids(Long gridMemberId) {
        List<GridDto> result = new ArrayList<>();
        List<GridMemberGridBindingDto> gridMemberGridBindingDtos =
                gridMemberGridBindingService.selectListByMemberId(gridMemberId);
        if (CollectionUtils.isNotEmpty(gridMemberGridBindingDtos)) {
            result = gridMemberGridBindingDtos
                    .stream()
                    .map(dto -> gridService.selectCacheById(dto.getGridId()))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 检查gridId在不在授权范围内
     *
     * @param gridMemberId
     * @param gridId
     * @return
     */
    public GridDto checkGridMemberPermission(Long gridMemberId, Long gridId) {
        if (gridMemberId == null || gridId == null) {
            return null;
        }
        List<GridDto> myGrids = getMyGrids(gridMemberId);
        Optional<GridDto> any = myGrids.stream().filter(gridDto -> gridId.equals(gridDto.getId())).findAny();
        return any.orElse(null);
    }

}
